<template>
  <div class="dropdown-container">
    <el-dropdown>
      <el-button>
        {{ selectedReportName }}
        <el-icon class="el-icon--right"><arrow-down /></el-icon>
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="report in reports"
            :key="report.reportId"
            :command="report.reportId"
            @click="handleDropDownMenuClick(report)"
          >
            {{ report.reportName }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
  <Suspense>
    <div style="display: flex">
      <div style="flex: 1">
        <div
          id="barChart"
          style="width: 600px; height: 400px; position: relative"
        ></div>
        <div
          id="pieChart"
          style="
            width: 600px;
            height: 400px;
            margin-top: 20px;
            position: relative;
          "
        ></div>
      </div>
      <div style="flex: 1; padding-left: 20px">
        <div
          id="radarChart"
          style="width: 600px; height: 400px; position: relative"
        ></div>
      </div>
    </div>
  </Suspense>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import * as echarts from "echarts";
import { ArrowDown } from "@element-plus/icons-vue";
import ProjectReportManagementService from "../api/ProjectReportManagemnet";

const reports = ref([]);
const selectedReportName = ref("");
let pieChart;
let barChart;
let radarChart;

const handleDropDownMenuClick = (report) => {
  selectedReportName.value = report.reportName;
  ProjectReportManagementService.getSubSystemById(report.reportId).then(
    (res) => {
      nextTick(() => {
        updatePieChart(res.data);
      });
    }
  );
  ProjectReportManagementService.getModulesByReportId(report.reportId).then(
    (res) => {
      nextTick(() => {
        updateBarChart(res.data);
      });
    }
  );
  ProjectReportManagementService.getReportContentByReportId(
    report.reportId
  ).then((res) => {
    nextTick(() => {
      updateRadarChart(res.data);
    });
  });
};

const initializePieChart = () => {
  const pieChartDom = document.getElementById("pieChart");
  if (pieChartDom) {
    pieChart =
      echarts.getInstanceByDom(pieChartDom) || echarts.init(pieChartDom);
  }
};

const initializeBarChart = () => {
  const barChartDom = document.getElementById("barChart");
  if (barChartDom) {
    barChart =
      echarts.getInstanceByDom(barChartDom) || echarts.init(barChartDom);
  }
};

const initializeRadarChart = () => {
  const radarChartDom = document.getElementById("radarChart");
  if (radarChartDom) {
    radarChart =
      echarts.getInstanceByDom(radarChartDom) || echarts.init(radarChartDom);
  }
};

const updatePieChart = (report) => {
  const chartData = report.map((item) => ({
    value: item.expense * item.expenseRatio,
    name: item.name,
  }));

  const pieOption = {
    title: {
      text: "项目子系统",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      top: "5%",
      left: "center",
    },
    series: [
      {
        name: "Expense Distribution",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData,
      },
    ],
  };
  pieChart.clear();
  pieChart.setOption(pieOption);
};

const transformData = (rawData) => {
  const result = [];
  const allModuleNames = new Set();
  rawData.forEach((subsystem) => {
    subsystem.modulesValue.forEach((module) => {
      allModuleNames.add(module.name);
    });
  });

  allModuleNames.forEach((moduleName) => {
    const series = {
      name: moduleName,
      type: "bar",
      stack: "",
      label: {
        show: true,
      },
      emphasis: {
        focus: "series",
      },
      data: [],
    };

    rawData.forEach((subsystem) => {
      const module = subsystem.modulesValue.find((m) => m.name === moduleName);
      if (module) {
        series.stack = subsystem.subsystemName;
        series.data.push(module.value);
      } else {
        series.data.push(null);
      }
    });

    result.push(series);
  });

  return result;
};

const updateBarChart = (modules) => {
  const yAxisData = modules.map((module) => module.subsystemName);
  const transformedData = transformData(modules);

  const barOption = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    legend: {},
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
    },
    yAxis: {
      type: "category",
      data: yAxisData,
    },
    series: transformedData,
  };

  barChart.clear();
  barChart.setOption(barOption);
};

const updateRadarChart = (contents) => {
  console.log("雷达图数据", contents);
  const data = contents;
  const maxValue = Math.max(...data.map((item) => item.percentage)) * 1.2;
  const indicators = data.map((item) => ({
    name: item.stage,
    max: maxValue,
  }));
  const values = data.map((item) => item.percentage);
  const radarOption = {
    title: {
      text: "工作量分配雷达图",
    },
    tooltip: {
      trigger: "item",
      formatter: function (params) {
        return `${params.seriesName}<br/>${params.name}: ${params.value}%`;
      },
    },
    legend: {
      data: ["项目进度"],
    },
    radar: {
      indicator: indicators,
    },
    series: [
      {
        name: "项目进度",
        type: "radar",
        areaStyle: {
          color: new echarts.graphic.RadialGradient(0.1, 0.6, 1, [
            {
              color: "rgba(255, 145, 124, 0.1)",
              offset: 0,
            },
            {
              color: "rgba(255, 145, 124, 0.9)",
              offset: 1,
            },
          ]),
        },
        data: [
          {
            value: values,
            name: "Progress",
          },
        ],
      },
    ],
  };

  radarChart.setOption(radarOption);
};

onMounted(() => {
  console.log("mounted");
  nextTick(() => {
    initializePieChart();
    initializeBarChart();
    initializeRadarChart();
  });

  ProjectReportManagementService.getReportIdAndReportName().then((res) => {
    reports.value = res.data;
    if (reports.value.length > 0) {
      selectedReportName.value = reports.value[0].reportName;
      ProjectReportManagementService.getSubSystemById(
        reports.value[0].reportId
      ).then((res) => {
        nextTick(() => {
          updatePieChart(res.data);
        });
      });
      ProjectReportManagementService.getModulesByReportId(
        reports.value[0].reportId
      ).then((res) => {
        nextTick(() => {
          updateBarChart(res.data);
        });
      });
      ProjectReportManagementService.getReportContentByReportId(
        reports.value[0].reportId
      ).then((res) => {
        nextTick(() => {
          updateRadarChart(res.data);
        });
      });
    }
  });
});
</script>

<style scoped>
#barChart,
#pieChart,
#radarChart {
  width: 600px !important;
  height: 400px !important;
  position: relative;
}
.dropdown-container {
  text-align: left;
}
.dropdown-button {
  outline: none;
}
</style>
